package legumes.shared.domain;

import java.io.Serializable;

public class Quantity implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private float value = 1f;
	private String unit = Unit.KG.toString();
	
	public Quantity() {
	}

	public Quantity(float value, String unitDisplayName_) {
		this.value = value;
		unit = Unit.fromDisplayName(unitDisplayName_).toString();
	}

	public Quantity(float value_, Unit unit_) {
		value = value_;
		unit = unit_.toString();
	}

	public Quantity(Quantity quantity) {
		this(quantity.getValue(), quantity.getUnitAsEnum());
	}

	public float getValue() {
		return value;
	}
	
	public void setValue(float value) {
		this.value = value;
	}

	public String getUnit() {
		return unit;
	}

	public Unit getUnitAsEnum() {
		return Unit.valueOf(getUnit());
	}

	public void setUnitAsEnum(Unit unit_) {
		setUnit(unit_.toString());
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

	@Override
	public String toString() {
		if (getUnitAsEnum().equals(Unit.UNITY)) {
			return String.valueOf(getValue());
		} else {
			return getValue() + " " + getUnitAsEnum().getDisplayName();
		}
	}

	public Quantity plus(Quantity quantity) {
		float f = quantity.getUnitAsEnum().convertTo(quantity.getValue(),
				getUnitAsEnum());
		setValue(getValue() + f);
		return this;
	}

	public Quantity minus(Quantity quantity) {
		float f = quantity.getUnitAsEnum().convertTo(quantity.getValue(),
				getUnitAsEnum());
		setValue(Math.max(0f, getValue() - f));
		return this;
	}

	public Quantity div(float v_) {
		float newVal = getValue() / v_;
		// computing based on integer if type is UNITY
		if (getUnitAsEnum().equals(Unit.UNITY)) {
			int nb = (int) newVal;
			if (nb > 0) {
				setValue(nb);
			}
		} else {
			setValue(newVal);
		}

		return this;
	}
}
